package com.learn.datainjector;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class TextFormat {
	public List<FieldData> getFieldDatas(String text,String name){
		List<String> lineTexts = getLineTexts(text);
		Map<String,String> dataMap = getDataMap(lineTexts);
		List<FieldData> fieldDatas = getFieldDatas(dataMap, name);
		return fieldDatas;
	}
	public List<String> getLineTexts(String text){
		List<String> result = new ArrayList<String>();
		String lines[] = text.split("\n");
		for (String line : lines) {
			line = line.trim().replace("\r", "");
			if(!line.isEmpty()&&line.charAt(0)!='#'){
				result.add(line);
			}
		}
		
		return result;
	}
	public Map<String,String> getDataMap(List<String> lines){
		Map<String,String> result = new HashMap<String, String>();
		for (String line : lines) {
			int keyIndex = line.indexOf("=");
			if(keyIndex != -1){
				String key = line.substring(0,keyIndex);
				String val = toValue(line.substring(keyIndex+1));
				result.put(key, val);
			}
		}
		return result;
	}
	public List<FieldData> getFieldDatas(Map<String,String> dataMap,String name){
		List<FieldData> result = new ArrayList<FieldData>();
		for(Entry<String, String> entry:dataMap.entrySet()){
			String key = entry.getKey();
			String val = entry.getValue();
			String fieldKeys[] = key.split("\\.");
			if(fieldKeys.length>1){
				FieldData fieldData = getFieldData(key,fieldKeys, name, val);
				if(fieldData!=null){
					result.add(fieldData);
				}
			}
		}
		return result;
	}
	
	public FieldData getFieldData(String key,String[] fieldKeys,String name,String fieldVal){
		if(fieldKeys.length <= 1){
			return null;
		}
		if(name == null){
			String[] nfieldKeys = new String[fieldKeys.length -1];
			System.arraycopy(fieldKeys, 1, nfieldKeys, 0, nfieldKeys.length);
			return new FieldData(key,fieldKeys[0], nfieldKeys, fieldVal);
		}else{
			if(fieldKeys[0].equals(name)){
				String[] nfieldKeys = new String[fieldKeys.length -1];
				System.arraycopy(fieldKeys, 1, nfieldKeys, 0, nfieldKeys.length);
				return new FieldData(key,name, nfieldKeys, fieldVal);
			}
		}
		return null;
	}
	
	
	private String toValue(String val){
		if(val.isEmpty()){
			return val;
		}
		val = val.replace("\\\"", "\"").trim();
		if(val.isEmpty()){
			return val;
		}
		String value = val;
		int length = val.length();
		int startIndex = 0;
		int endIndex = length-1;
		int xendIndex = endIndex;
		if(length>0&&value.charAt(startIndex) == '"'){
			startIndex++;
		} 
		if(length>1&&value.charAt(endIndex) == '"'){
			endIndex--;
		}
		if(startIndex!=0||endIndex!=xendIndex){
			value = val.substring(startIndex,endIndex+1);
		}
		return value;
	}
	
	public static void main(String[] args) {
		TextFormat textFormat = new TextFormat();
		System.out.println(textFormat.toValue("\"  \""));
	}
}
